package com.atguigu.daijia.order.listener;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @create: 2024/10/3
 * @author: gyhe10
 * @description: 监听订单延迟队列的消息
 **/

@Slf4j
@Component
@RequiredArgsConstructor
public class RedisDelayListener {

    private final RedissonClient redissonClient;
    private final OrderInfoService orderInfoService;

    @PostConstruct
    public void orderDelayListener() {
        new Thread(() -> {
            log.info("监听订单延迟队列的消息开始");
            while (true) {
                RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(RedisConstant.ORDER_DELAY_QUEUE);
                String orderId = null;
                try {
                    orderId = blockingQueue.take();
                    if (StringUtils.hasText(orderId)) {
                        log.info("监听到订单延迟队列的消息，订单 ID：{}", orderId);
                        orderInfoService.cancelOrder(Long.valueOf(orderId));
                    }
                } catch (InterruptedException e) {
                    log.error("监听订单延迟队列的消息异常");
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
